<?php
/**
 * Created by PhpStorm.
 * User: J.H
 * Date: 2017/4/10
 * Time: 0:13
 */

namespace lib\oauth\wechat;


use lib\curl\HttpRequest;
use lib\oauth\OauthBase;

class WechatConnect extends OauthBase
{
    private $url_api = 'https://api.weixin.qq.com/';
    private $url_login = 'https://open.weixin.qq.com/connect/';
    private $app_id;
    private $app_secret;
    private $app_callback;
    private $api_scope = 'snsapi_login';
    protected $access_token;
    protected $openid;
    protected $unionid;

    function __construct($config = array('appId' => '', 'appSecret' => '', 'callback' => ''))
    {
        parent::__construct();
        $this->app_id = $config['appId'];
        $this->app_secret = $config['appSecret'];
        $this->app_callback = $config['callback'];
    }

    function login()
    {
        $state = $this->setState('wec');
        $params = array(
            'response_type' => 'code',
            'appid' => $this->app_id,
            'redirect_uri' => $this->app_callback,
            'state' => $state,
            'scope' => $this->api_scope
        );
        $login_url = $this->parseUrl($this->url_login, 'qrconnect', $params);
        $this->to($login_url);
    }

    function getOpenid()
    {
        $this->getAccessToken();
        if ($this->unionid) {
            return $this->unionid;
        }
        return $this->openid;

    }

    function state()
    {
        $state = parent::getState('wec');
        if (null === $state) {
            return $this->setState('wec');
        }
        return $state;
    }

    private function getAccessToken()
    {
        if ($this->access_token) {
            return $this->access_token;
        }
        $state = parent::getState('wec');
        if (isset($_GET['state']) && $_GET['state'] !== $state) {
            $this->error(0);
        }
        if (!isset($_GET['code'])) {
            $this->error(1);
        }
        if (empty($_GET['code']) && empty($_GET['state'])) {
            $this->login();
        }
        $params = array(
            'grant_type' => 'authorization_code',
            'appid' => $this->app_id,
            'secret' => $this->app_secret,
            'code' => $_GET['code']
        );
        $url = $this->parseUrl($this->url_api, 'sns/oauth2/access_token', $params);
        $result = HttpRequest::get($url, array(), $ret_code, $error_msg);
        if ($error_msg) {
            $this->error(2, $error_msg);
        }
        if ($result = json_decode($result, true)) {

            if (isset($result['access_token'])) {
                $this->openid = $result['openid'];
                if (isset($result['unionid'])) {
                    $this->unionid = $result['unionid'];
                }
                return $this->access_token = $result['access_token'];
            }
        }
        return '';
    }

    /**
     * @link https://open.weixin.qq.com/cgi-bin/showdocument?action=dir_list&t=resource/res_list&verify=1&id=open1419316518
     *
     * @param string $lang
     *
     * @return array
     */
    function getUserInfo($lang = 'zh-CN')
    {
        $params = array(
            'openid' => $this->getOpenid(),
            'access_token' => $this->getAccessToken(),
            'lang' => $lang
        );
        $api = $this->parseUrl($this->url_api, 'sns/userinfo', $params);
        $result = HttpRequest::get($api, array(), $ret_code, $error_msg);
        if ($error_msg) {
            $this->error(2, $error_msg);
        }
        if (!$user_info = json_decode($result, true)) {
            return array();
        }
        return $user_info;
    }
}